package com.example.ggpicturegg.bottom;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.ggpicturegg.Mysql_com.Mysql_tool;
import com.example.ggpicturegg.R;
import com.example.ggpicturegg.first.RecyclerviewActivity;
import com.example.ggpicturegg.ftpUD.UpAndDown;
import com.example.ggpicturegg.tool.Loaddata;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Myinfo extends AppCompatActivity {

    private TextView frist;
    private  TextView talk;
    private  TextView friend;
    private ImageView im_add_x;
    private ImageView Tv_imageView;
    private Bitmap imageBlol_all;
    private String FirePath_;
    private String  fireName_local;

    private Bundle bundle1;
    private String sss=null;
    private String judge_name;
    private Handler mainHandler;

    public static final int CHOOSER_PICTURE = 2;

    private static final int REQUEST_CODE_SELECT_IMAGE = 4;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myinfo);

        initView();
        judge();


    }
    private void judge(){
        Mysql_tool tool = new Mysql_tool();
        new Thread(new Runnable() {
            @Override
            public void run() {
                judge_name = tool.getname(sss);

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (judge_name == sss){
                            System.out.println("printf(-----数据库有这个名字的图片---   "+judge_name+"    ---------)");
                            showhead();
                        }
                        if(judge_name==""){
                            System.out.println("printf(-----数据库没有这个名字的图片---   "+judge_name+"    ---------)");
                        }
                    }
                });
            }
        }).start();

    }
    private void showhead(){
        //  图片展示
        new Thread(new Runnable() {
            @Override
            public void run() {

                Bitmap bitmap =  Loaddata.getImage(sss+".jpg",0);
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Tv_imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
    private void initView(){
        im_add_x = findViewById(R.id.add_x);
        frist = findViewById(R.id.frist_x);
        talk = findViewById(R.id.talk_x);
        friend = findViewById(R.id.friend_x);
        Tv_imageView = findViewById(R.id.h_head);
        OnClick onClick = new OnClick();
        mainHandler = new Handler(getMainLooper());
        transinfo();
        frist.setOnClickListener(onClick);
        talk.setOnClickListener(onClick);
        friend.setOnClickListener(onClick);
        im_add_x.setOnClickListener(onClick);
        Tv_imageView.setOnClickListener(onClick);
    }


    private void transinfo(){
        bundle1 = getIntent().getExtras();
        sss = bundle1.getString("Re_to_myinfo");
        if(sss!=null){Log.d("Myinfo 接受 Re 的name", "    ---------- is ---------    "+ sss);}
        if(sss==null){
            sss = bundle1.getString("friend_to_myinfo");
            if(sss!=null){ Log.d("Myinfo 接受 Friend 的name", "    ---------- is ---------    "+ sss);}
        }
        if(sss==null){
            sss = bundle1.getString("talk_to_myinfo");
            if(sss!=null){ Log.d("Myinfo 接受 talk 的name", "    ---------- is ---------    "+ sss);}
        }
        if(sss==null){
            sss = bundle1.getString("care_to_myinfo");
            if(sss!=null){Log.d("Myinfo 接受 care 的name", "    ---------- is ---------    "+ sss);}
        }
        if(sss==null){
            sss = bundle1.getString("like_to_myinfo");
            if(sss!=null){ Log.d("Myinfo 接受 like 的name", "    ---------- is ---------    "+ sss);}
        }
    }

    // 增加照片
    private  void AddImage(){
        if( (ContextCompat.checkSelfPermission(Myinfo.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED))
        {
            ActivityCompat.requestPermissions(Myinfo.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else {
            openAlbum();
        }
    }

    //自动打开相册
    private void openAlbum() {
        Intent intent =new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSER_PICTURE);
    }

    // 选择图片
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
        }
    }

    // 处理权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length >0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else {
                    Toast.makeText(Myinfo.this,"用户拒绝你的权限请求",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectImage();
            } else {
                Toast.makeText(this, "没有权限!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        switch (requestCode){
            case CHOOSER_PICTURE:
                if (resultCode==RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        handleImageOnKitkat(data);
                    }else {
                        handleImagebeforeKitkat(data);
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //获取sdk小于19的访问权
    private void handleImagebeforeKitkat(Intent data) {
        Uri uri=data.getData();
        String imagepath=getimagepath(uri,null);
        FirePath_ = imagepath;
        System.out.println("-------------imagepath -----123-----is    "+imagepath);
        displayImage(imagepath);
    }

    //获取sdk版本大于19的访问权限
    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagepath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId=DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagepath=getimagepath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downlo ads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads"),Long.valueOf(docId));
                imagepath=getimagepath(contentUri,null);
            }else if ("content".equalsIgnoreCase(uri.getScheme())){
                imagepath=getimagepath(uri,null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagepath=uri.getPath();

            }
            FirePath_ = imagepath;
            System.out.println("-------------imagepath -----789-----is    "+FirePath_);
            displayImage(imagepath);

        }
    }

    //展示图片
    private void displayImage(String imagepath) {
        System.out.println("--------------- firePath_local is  :"+FirePath_);
        String[] words=FirePath_.split("/");
        int len = words.length - 1;
        System.out.println("-------------file ----------is    "+words[len]);
        fireName_local = words[len];
        if (imagepath!=null){
            Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
            imageBlol_all = bitmap;
            Tv_imageView.setImageBitmap(bitmap);
        }else {
            Toast.makeText(this,"用户选择图像失败",Toast.LENGTH_SHORT).show();
        }

       // 存入ftp
        upload();
    }

    private void Upload() {
        final Mysql_tool tool1 = new Mysql_tool();
        final String firename = sss+".jpg";
        new Thread(new Runnable() {
            @Override
            public void run() {
                tool1.add_name_image(sss,firename);
                System.out.println("                 添加成功               ！！！");
            }
        }).start();

    }


    //获取图片路径
    private String getimagepath(Uri uri, String selection) {
        String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if (cursor.moveToNext()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void judge_name(){
        Mysql_tool tool = new Mysql_tool();
        new Thread(new Runnable() {
            @Override
            public void run() {
                judge_name = tool.getname(sss);

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (judge_name == sss){
                            System.out.println("printf(--------   "+judge_name+"    ---------)");
                        }
                        if(judge_name==""){
                            Upload();
                        }
                    }
                });
            }
        }).start();

    }

    private void upload(){
        final Mysql_tool tool1 = new Mysql_tool();
        final String firename =sss + ".jpg";
        new Thread(new Runnable() {
            @Override
            public void run() {
                String sF = UpAndDown.ftpUpload(FirePath_,firename,0);
                if(sF=="1"){
                    // 数据库操作
                    judge_name();
                }
                else{
                    System.out.println("------------------    Error                 ");
                }
            }
        }).start();

    }
    class OnClick implements View.OnClickListener {
        private Intent intent;
        private Bundle bundle;

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.frist_x:
                    intent = new Intent(Myinfo.this, RecyclerviewActivity.class);
                    Log.d("Myinfo 发送 Re 的name", "    ---------- is ---------    "+ sss);
                    bundle = new Bundle();
                    //bundle.putInt("max_id",ans);
                    bundle.putString("myinfo_to_Re",sss);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.friend_x:
                    intent = new Intent(Myinfo.this, Friend_b.class);
                    Log.d("Myinfo 发送 Friend 的name", "    ---------- is ---------    "+ sss);
                    bundle = new Bundle();
                    //bundle.putInt("max_id",ans);
                    bundle.putString("myinfo_to_friend",sss);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.talk_x:
                    intent = new Intent(Myinfo.this, Talk_b.class);
                    Log.d("Myinfo 发送 talk 的name", "    ---------- is ---------    "+ sss);
                    bundle = new Bundle();
                    //bundle.putInt("max_id",ans);
                    bundle.putString("myinfo_to_talk",sss);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.add_x:
                    intent = new Intent(Myinfo.this, Publish_b.class);
                    bundle = new Bundle();
                    //bundle.putInt("max_id",ans);
                    bundle.putString("myinfo_to_add",sss);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.h_head:
                    AddImage();
                    break;
            }
        }
    }


}